package com.arm.service.impl;

import com.arm.dao.ConsigneeInfoMapper;
import com.arm.module.ConsigneeInfo;
import com.arm.service.ConsigneeInfoService;
import com.arm.tools.myRunTime.MyRunTimeExcption;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by Baggio on 2017-12-8.
 */
@Service
public class ConsigneeInfoServiceImpl implements ConsigneeInfoService {
    @Autowired
    private ConsigneeInfoMapper consigneeInfoMapper;

    private void insertConsigneeInfo(ConsigneeInfo consigneeInfo) {
        consigneeInfoMapper.insertConsigneeInfo(consigneeInfo);
    }

    private void updateConsigneeInfo(ConsigneeInfo consigneeInfo) {

        ConsigneeInfo consigneeInfo1 = consigneeInfoMapper.selectConsigneeInfoById(consigneeInfo.getTid());

        if (consigneeInfo1 == null) {
            insertConsigneeInfo(consigneeInfo);
            return;
        }
        if (StringUtils.isNotBlank(consigneeInfo.getConsigneePhone())) {
            consigneeInfo1.setConsigneePhone(consigneeInfo.getConsigneePhone());
        }
        if (StringUtils.isNotBlank(consigneeInfo.getConsigneeAddress())) {
            consigneeInfo1.setConsigneeAddress(consigneeInfo.getConsigneeAddress());
        }
        if (StringUtils.isNotBlank(consigneeInfo.getConsigneeName())) {
            consigneeInfo1.setConsigneeName(consigneeInfo.getConsigneeName());
        }

        consigneeInfoMapper.updateConsigneeInfoById(consigneeInfo1);
    }

    @Override
    public void modifyConsigneeInfo(ConsigneeInfo consigneeInfo) throws MyRunTimeExcption {
        if (consigneeInfo == null) {
            throw new MyRunTimeExcption("收货人信息为空！");
        }
        Long  orderId=consigneeInfo.getOrderId();
        if(orderId==null){
            throw new MyRunTimeExcption("订单Id为空！");
        }
        ConsigneeInfo consigneeInfoTemp=  consigneeInfoMapper.selectConsigneeInfoByOrderId(orderId);
        if (consigneeInfoTemp== null) {
            consigneeInfo.setCreateTime(new Date());
            insertConsigneeInfo(consigneeInfo);
            return;
        }
        consigneeInfoTemp.setConsigneeAddress(consigneeInfo.getConsigneeAddress());
        consigneeInfoTemp.setConsigneeName(consigneeInfo.getConsigneeName());
        consigneeInfoTemp.setConsigneePhone(consigneeInfoTemp.getConsigneePhone());
        updateConsigneeInfo(consigneeInfoTemp);
    }

    @Override
    public ConsigneeInfo selectConsigneeInfoByOrderId(Long orderId) throws MyRunTimeExcption {
        return consigneeInfoMapper.selectConsigneeInfoByOrderId(orderId);
    }
}
